//
//  UserProfileViewController.m
//  Mecca
//
//  Created by Nico Villanueva iOS Dev on 24/7/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "UserProfileViewController.h"

#import "UIManager.h"

#import "ParserClass.h"

#import "UserDetails.h"

#import "PostClass.h"

#import "AudioPlayManager.h"

#import "LocalPlayerClass.h"

#import "PlayListViewController.h"

#import "PlaySongListViewController.h"

#import "EditProfileViewController.h"

#import "AppDelegate.h"

#import "GlobalVariables.h"

#import "IIViewDeckController.h"

@interface UserProfileViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate>
    
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet FBProfilePictureView *profilePictureView;
@property (strong, nonatomic) IBOutlet FBLoginView *fbLoginView;
@property (strong, nonatomic) NSString *objectID;



@end

@implementation UserProfileViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)updateSuperView{
    
    NSLog(@"Updating");
    
    UserDetails *userd = [[ParserClass sharedItems] userDetails][0];
    [self showImage:[userd image]];
    [self setImageString:[userd image]];
    
}

- (IBAction)scanQRAction:(id)sender {
    
    NSLog(@"Scannning QR Code");
    
    self.viewDeckController.centerController = [[UIManager sharedItems] scanViewController];
    [self.viewDeckController closeRightViewAnimated:YES];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"userProfileView" object:nil];
    
    // Do any additional setup after loading the view from its nib

    
    [_fbLoginView setReadPermissions:@[@"public_profile"]];
    [_fbLoginView setDelegate:self];
    _objectID = nil;
    
    GlobalVariables *gVar = [GlobalVariables sharedItems];
    
    NSLog(@"Login Status = %@", gVar.loginType);
    
    
    if ([gVar.loginType isEqualToString:@"fb"]) {
        self.btnSettings.hidden = YES;
        self.btnSettings.alpha = 0;
        self.btnSettings.userInteractionEnabled = NO;
        self.fbLoginView.alpha = 1;
        self.fbLoginView.userInteractionEnabled = YES;
        self.btnLogoutProp.alpha = 0;
        self.btnLogoutProp.userInteractionEnabled = NO;
        
        
    }else if([gVar.loginType isEqualToString:@"normal"]){
        self.btnSettings.hidden = NO;
        self.fbLoginView.alpha = 0;
        self.fbLoginView.userInteractionEnabled = NO;
        self.btnLogoutProp.alpha = 1;
        self.btnLogoutProp.userInteractionEnabled = YES;
    }
    
    [self updatingAllView];
    
}

- (void) updatingAllView{
    
    
    UserDetails *userd = [[ParserClass sharedItems] userDetails][0];
    
    self.lblUsername.text = [userd dname];
    self.lblUserNumber.text = [userd contact];
    self.lblUserCredits.text = [userd credits];
    [self showImage:[userd image]];
    [self setImageString:[userd image]];
    
    
    
    NSLog(@"User Name: %@", [userd dname]);


}

-(void) somethingHappens:(NSNotification*) notification
{
    NSLog(@"notification = %@",[notification object]);
    
    [self updatingAllView];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

}


- (void)setImageString:(NSString *)strImage{
    NSString *strImg = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@",strImage];
    
    [NSThread detachNewThreadSelector:@selector(showImage:) toTarget:self withObject:strImg];
}

- (IBAction)btnEditProfile:(id)sender {
    
    [self.view addSubview:[[[UIManager sharedItems] editProfileViewController] view]];
}

- (IBAction)btnBuyLoads:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://192.185.2.177/~tapdash/projects/musicapp"]];
}






-(void)showImage:(NSString*)imageShow{
    
    
    @autoreleasepool {
        NSData *imageList = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageShow]];
        [self.imgProfilePic setAlpha:0];
         [self.actLoading setHidden:NO];
        [UIView animateWithDuration:1 animations:^{
            
            UIImage *image = [UIImage imageWithData:imageList];

            self.imgProfilePic.image = image;
            [self.actLoading setHidden:YES];
            [self.imgProfilePic setAlpha:1];

        } completion:^(BOOL finished) {
            
        }];
        
    }
}



- (IBAction)btnLogout:(id)sender {
    

    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
    [lp.audioPlayer stop];
    

//    self.actLoading.hidden = NO;
    

    UserDetails *user = [[ParserClass sharedItems] userDetails][0];
    
    
//    NSDictionary *logOutDict =
    
    self.receivedData = [NSMutableData data];
    NSURLRequest *request = [[PostClass sharedItems] logOutWithSessionID:[user sessionID]];
    _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    
    [self.activityView setHidden:NO];
    [self.logInOutLbl setHidden:NO];

    
}


#pragma mark - UITextField Delegate

-(BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder];

    return YES;
}


#pragma mark - Facebook Data Fetch Method


// This method will be called when the user information has been fetched after login
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user {
    
    self.profilePictureView.profileID = user.objectID;
    self.nameLabel.text = user.name;
    
    
    
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        
        if (!(_receivedData == nil)) {
            
            NSDictionary *logOutDict = [NSJSONSerialization JSONObjectWithData:_receivedData options:kNilOptions error:nil];
            
            
            if ([[[logOutDict objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
                [[ParserClass sharedItems] emptyData];
                // [((AppDelegate*)[[UIApplication sharedApplication] delegate]) deleteAllObjectsInCoreData];
                
                GlobalVariables *vGloba = [GlobalVariables sharedItems];
                vGloba.loginType = @"normal";
                
                [[UIManager sharedItems] logOut];
                
                [self.activityView setHidden:NO];
                [self.logInOutLbl setHidden:NO];
                
            }else{
                
                
                NSLog(@"Logout");
                
                UIAlertView *alr  = [[UIAlertView alloc]initWithTitle:@"" message:@"You Are Successfuly Logout" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                
                [alr show];
                
                self.actLoading.hidden = YES;
                
                [[ParserClass sharedItems] emptyData];
                [[UIManager sharedItems] logOut];
                
                [self.activityView setHidden:NO];
                [self.logInOutLbl setHidden:NO];
                
            }

            
            
        }
        
        
        NSLog(@"Finish");
    }
    
}



@end
